package com.changgou.config.service.impl;

import com.changgou.config.dao.FreightTemplateMapper;
import com.changgou.config.pojo.FreightTemplate;
import com.changgou.config.service.FreightTemplateService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;
@Service
public class FreightTemplateServiceImpl  implements FreightTemplateService {
    //注入mapper
    @Autowired
    private FreightTemplateMapper freightTemplateMapper;
    @Override
    public List<FreightTemplate> findAll() {
        return freightTemplateMapper.selectAll();
    }

    @Override
    public FreightTemplate findById(Integer id) {
        return freightTemplateMapper.selectByPrimaryKey(id);
    }

    @Override
    public void add(FreightTemplate freightTemplate) {
     freightTemplateMapper.insert(freightTemplate);
    }

    @Override
    public void update(FreightTemplate freightTemplate) {
      freightTemplateMapper.updateByPrimaryKey(freightTemplate);
    }

    @Override
    public void delete(Integer id) {
    freightTemplateMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<FreightTemplate> findList(Map<String, Object> searchMap) {
        Example example =createExample(searchMap);

        return freightTemplateMapper.selectByExample(example);
    }

    @Override
    public Page<FreightTemplate> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<FreightTemplate>) freightTemplateMapper.selectAll();
    }

    @Override
    public Page<FreightTemplate> findPage(Map<String, Object> searchMap, int page, int size) {
        Example example =createExample(searchMap);
        PageHelper.startPage(page, size);
        return (Page<FreightTemplate>) freightTemplateMapper.selectByExample(example);
    }
    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(FreightTemplate.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 模板名称
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                criteria.andLike("name","%"+searchMap.get("name")+"%");
            }
            // 计费方式
            if(searchMap.get("type")!=null && !"".equals(searchMap.get("type"))){
                criteria.andLike("type","%"+searchMap.get("type")+"%");
            }

            // ID
            if(searchMap.get("id")!=null ){
                criteria.andEqualTo("id",searchMap.get("id"));
            }

        }
        return example;
    }
}
